/**
 * 用户服务 - 处理登录、注册和用户状态管理
 * 使用 uniCloud 云函数进行用户认证
 */

// 用户数据存储键名
const USER_STORAGE_KEY = "walking-c-user-storage";
const TOKEN_STORAGE_KEY = "walking-c-token";

// 用户服务
export const userService = {
  // 当前登录用户
  currentUser: null,

  // 初始化，从本地存储加载用户数据
  init() {
    const userStr = uni.getStorageSync(USER_STORAGE_KEY);
    const tokenStr = uni.getStorageSync(TOKEN_STORAGE_KEY);

    if (userStr && tokenStr) {
      try {
        this.currentUser = JSON.parse(userStr);
      } catch (e) {
        this.currentUser = null;
        uni.removeStorageSync(USER_STORAGE_KEY);
        uni.removeStorageSync(TOKEN_STORAGE_KEY);
      }
    }
  },

  // 检查是否已登录
  isLoggedIn() {
    return !!this.currentUser && !!uni.getStorageSync(TOKEN_STORAGE_KEY);
  },

  // 账号密码登录
  async login(username, password) {
    try {
      // 调用云函数实现登录
      const result = await uniCloud.callFunction({
        name: "loginCUser",
        data: {
          username,
          password,
        },
      });

      // 云函数返回结果
      const response = result.result;

      if (response.code === 0) {
        // 登录成功，存储用户信息和令牌
        this.currentUser = response.data.userInfo;
        const token = response.data.token;

        // 保存到本地存储
        uni.setStorageSync(USER_STORAGE_KEY, JSON.stringify(this.currentUser));
        uni.setStorageSync(TOKEN_STORAGE_KEY, token);

        return this.currentUser;
      } else {
        throw response.message;
      }
    } catch (error) {
      console.error("登录失败:", error);
      throw typeof error === "string" ? error : "登录失败，请稍后再试";
    }
  },

  // 手机号登录 (不使用短信验证)
  async phoneLogin(phone) {
    try {
      // 调用云函数实现手机号登录
      const result = await uniCloud.callFunction({
        name: "loginCUser",
        data: {
          phone,
        },
      });

      const response = result.result;

      if (response.code === 0) {
        // 登录成功，存储用户信息和令牌
        this.currentUser = response.data.userInfo;
        const token = response.data.token;

        // 保存到本地存储
        uni.setStorageSync(USER_STORAGE_KEY, JSON.stringify(this.currentUser));
        uni.setStorageSync(TOKEN_STORAGE_KEY, token);

        return this.currentUser;
      } else {
        throw response.message;
      }
    } catch (error) {
      console.error("手机号登录失败:", error);
      throw typeof error === "string" ? error : "手机号登录失败，请稍后再试";
    }
  },

  // 注册
  async register(username, password) {
    try {
      // 调用云函数实现注册
      const result = await uniCloud.callFunction({
        name: "registerCUser",
        data: {
          username,
          password,
        },
      });

      // 云函数返回结果
      const response = result.result;

      if (response.code === 0) {
        return true;
      } else {
        throw response.message;
      }
    } catch (error) {
      console.error("注册失败:", error);
      throw typeof error === "string" ? error : "注册失败，请稍后再试";
    }
  },

  // 手机号注册 (不使用短信验证)
  async phoneRegister(phone, password, nickname, gender = 0) {
    try {
      // 调用云函数实现手机号注册
      const result = await uniCloud.callFunction({
        name: "registerCUser",
        data: {
          phone,
          password,
          nickname,
          gender,
        },
      });

      const response = result.result;

      if (response.code === 0) {
        return true;
      } else {
        throw response.message;
      }
    } catch (error) {
      console.error("手机号注册失败:", error);
      throw typeof error === "string" ? error : "手机号注册失败，请稍后再试";
    }
  },

  // 登出
  logout() {
    this.currentUser = null;
    uni.removeStorageSync(USER_STORAGE_KEY);
    uni.removeStorageSync(TOKEN_STORAGE_KEY);

    // 跳转到登录页
    uni.reLaunch({
      url: "/pages/login/login",
    });
  },

  // 获取当前用户信息
  getCurrentUser() {
    return this.currentUser;
  },

  // 检查是否需要登录
  checkLoginStatus() {
    return new Promise((resolve, reject) => {
      if (this.isLoggedIn()) {
        resolve(this.currentUser);
      } else {
        reject("未登录");
      }
    });
  },
};

// 导出单例
export default userService;
